package com.dingyx.ps.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 功能描述:
 * 〈Excel 导入导出工具类〉
 * @author : ZhangYang
 * @date : 2019/11/20 17:38
 */
@Slf4j
public class ExcelUtils {


    /**
     * 〈根据模板生成Excel，并直接返回前端供用户下载〉
     * @param templateUrl   模板URL
     * @param data          模板数据
     * @param fileName      用户下载的文件名称（不带拓展名）
     * @author ZhangYang
     * @date 2020/12/30 10:32
     * @version 1.0.0
     */
    public static void downLoadExcelByTemplate(String templateUrl,Map<String,Object> data, String fileName){
        try {
            TemplateExportParams tep = new TemplateExportParams(templateUrl,true);
            Workbook workbook = ExcelExportUtil.exportExcel(tep, data);
            //下载文件
            downLoadExcel(fileName,workbook);
        }catch (Exception e){
            log.error(ExceptionUtil.getMessage(e));
        }
    }

    /**
     * 〈将文件返回给前端客户〉
     * @param fileName 文件名称
     * @param workbook excel数据
     * @author ZhangYang
     * @date 2020/12/30 10:36
     * @version 1.0.0
     */
    public static void downLoadExcel(String fileName, Workbook workbook) throws IOException {
        try {
            HttpServletResponse response = HttpServletUtils.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {
        XLS("xls"), XLSX("xlsx");
        private String value;
        ExcelTypeEnum(String value) {
            this.value = value;
        }
        public String getValue() {
            return value;
        }
    }
}
